<script setup>
import {ref, onMounted, onBeforeUnmount, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import axios from "axios";
import * as echarts from 'echarts';

const chartEl = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  try {
    if (chartInstance) {
      chartInstance.dispose()
    }

    // 确保容器存在且可见
    if (!chartEl.value || chartEl.value.offsetHeight === 0) {
      setTimeout(initChart, 50)
      return
    }

    chartInstance = echarts.init(chartEl.value)
    const baseOption = {
      title: {text: '用户增长趋势', left: 'center'},
      tooltip: {trigger: 'axis'},
      xAxis: {
        type: 'category',
        name: '日期',
        axisLabel: {rotate: 45}
      },
      yAxis: {
        type: 'value',
        name: '用户数量',
        minInterval: 1
      },
      series: [{
        name: '新增用户',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: 'rgba(64, 158, 255, 0.8)'},
            {offset: 1, color: 'rgba(64, 158, 255, 0.1)'}
          ])
        },
        itemStyle: {
          color: '#409EFF'
        }
      }],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      }
    }
    chartInstance.setOption(baseOption)

    // 添加窗口resize监听
    window.addEventListener('resize', () => {
      chartInstance?.resize()
    })
  } catch (error) {
    console.error('图表初始化失败:', error)
    ElMessage.error('图表初始化失败')
  }
}


const tableData = ref([])


const queryParams = ref({
  startDate: '',
  endDate: ''
})

const updateChart = (dates, counts) => {
  // 完整配置更新
  const option = {
    xAxis: {data: dates},
    series: [{
      data: counts,
      // 必须保持完整的series配置
      type: 'line',
      smooth: true,
      areaStyle: {},
      itemStyle: {
        color: '#409EFF'
      }
    }]
  }

  // 添加 notMerge 参数确保配置更新
  chartInstance.setOption(option, {notMerge: false})

  // 同步表格数据
  tableData.value = dates.map((date, index) => ({
    date,
    count: counts[index]
  }))

  // 强制重绘
  chartInstance.resize()
}
const fetchData = () => {
  console.log('开始时间', {params: queryParams.value})
  axios.get(BASE_URL + '/p1/admin/stats/user-growth', {params: queryParams.value}).then(
      response => {
        if (response.data.code == 2000) {
          updateChart(response.data.data.dates, response.data.data.counts);
        } else {
          ElMessage(response.data.msg);
        }
      }
  )
}
// 更新图表

const endDateDisabled = (time) => {
  return queryParams.value.startDate
      ? time < new Date(queryParams.value.startDate)
      : false
}
onMounted(() => {
  nextTick(() => {
    initChart()
    fetchData()
  })
})
const resetSearch = () => {
  queryParams.value = {
    startDate: '',
    endDate: ''
  }
  fetchData()
}
</script>

<template>
  <div style="height: 6vh;background-image: linear-gradient(to right, #fffacd, #add8e6);padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;;font-weight: bold">用户增长统计</span>
  </div>
  <!--  搜索栏-->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="开始日期">
        <el-date-picker
            v-model="queryParams.startDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="结束日期" style="width:290px;">
        <el-date-picker
            v-model="queryParams.endDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            :disabled-date="endDateDisabled"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!--数据统计图-->
  <el-card style="margin:20px;">
    <el-table :data="tableData">
      <el-table-column prop="date" label="日期" width="180"/>
      <el-table-column prop="count" label="用户数变化"/>
    </el-table>
  </el-card>
  <!-- 统计图表 -->
  <el-card style="margin:20px;">
    <div ref="chartEl" class="chart-container"></div>
  </el-card>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 500px; /* 添加固定高度 */
  margin: 20px;
  background: #fff;
}
</style>